"""
按周期计算收益率，简单方法
"""
class top_byobjs:
    def __init__(self,ascending=False,top=0.2,isna=True):
        self.ascending=ascending
        self.top=top
        self.isna=isna
    def oncalc(self,d,timekey=None):
        f=d.copy()
        f.sort_values(ascending=self.ascending,inplace=True)
        n = len(f)
        if not self.isna:
            f1 = f.loc[f.isna()]
            n=n-len(f1)
        n=int(n*self.top)
        if n>1:
            f2=f[:n]
            f.loc[:]=False
            f.loc[f2.index]=True
        else:
            f.loc[:] = False
        return f

if __name__ == '__main__':
    from mohe.dataset import dataset
    from research.calcor.calcors_graph import graph_calcor,graph_calcor_axis1
    cc = [{'calc_cmd': 'class', "class": "ror", "out": ["ror10"], "init_args": {"timeperiod": 10},"input":["close"]}]

    cc1 = [{'calc_cmd': 'class', "class": "top", "out": ["top20"],"input":["ror10"],"init_args": {"ascending":False,"top":0.2,"isna":False},"in_isdf":True,"out_isdf":True}
           ]
    c1 = graph_calcor_axis1(cc1)
    datatool0 = dataset(product="stock", datatype="k1d", baseurl=r"G:\price", region="C", fqtype="hfq",
                        source=None)
    pretk=None
    data={}
    data1={}
    stock_c={}
    for _,t in datatool0.iter_price("all", "20200103"):
        tk=t["timekey"]
        obj=t["obj"]
        if pretk:
            if pretk!=tk:
                data1=c1.onbar(data)
                data={}
                pretk=tk
        else:
            pretk=tk
        if obj not in stock_c.keys():
            stock_c[obj]= graph_calcor(cc)
        t=stock_c[obj].onbar(t)
        data[obj]=t

